/**
 * Created by sky on 2019/3/11.
 */
layui.define(['mobile','zepto', 'justchatSocketMgr'], function (exports) {
    var mobile = layui.mobile
        , $ = layui.zepto
        , justchatSocketMgr = layui.justchatSocketMgr
        , layim = mobile.layim
        , layer = mobile.layer;

    var cache = layim.cache();
    var local = cache.local;
    var mine = cache.mine;
    var chatlog = local.chatlog;
    var history = local.history;
    var friendsInfo = JSON.parse(localStorage.getItem("friendsInfo")) || {};
    var isAgency = window.location.search.includes('role=agent')

    var target_id = justchatSocketMgr.getParam('target_id')

    var _msgIsInChatlog = function (clientID, source) {
        var result = false;
        var key = "friend" + source;
        var chatlog = _getChatlog();
        if (chatlog) {
            console.log("source=" + source);
            var chatlogBykey = chatlog[key];
            if (chatlogBykey) {
                var len = chatlogBykey.length;
                if (len > 0) {
                    for (var i = 0; i < len; i++) {
                        var curClientID = chatlogBykey[i].cid;
                        if (curClientID && clientID == curClientID) {
                            result = true;
                            break;
                        }
                    }
                }
            }
        }
        return result;
    };

    var _getHistory = function () {
        var history = null;
        var obj = {};
        if (localStorage.getItem("layim-mobile") && localStorage.getItem("layim-mobile") != "{}") {
            obj = JSON.parse(localStorage.getItem("layim-mobile"));
            history = obj[mine.id].history;
        }
        return history;
    };

    var _getChatlog = function () {
        var chatlog = null;
        var obj = {};
        if (localStorage.getItem("layim-mobile") && localStorage.getItem("layim-mobile") != "{}") {
            obj = JSON.parse(localStorage.getItem("layim-mobile"));
            if(obj[mine.id]){
                chatlog = obj[mine.id].chatlog;
            } else {
                chatlog = obj[mine.id] = {chatlog: {}}
            }
        }
        return chatlog;
    };

    var _getMaxID = function (topic_id) {
        var maxMsgID = 0;
        var obj = {};
        if (localStorage.getItem("maxInfo")) {
            obj = JSON.parse(localStorage.getItem("maxInfo"));
            maxMsgID = obj["friend" + topic_id]
        }
        return maxMsgID || 0;
    };

    var justchatFunc = {
        //接受的消息（7）
        justchatGetMessage: function (data, justchatCustom) {
            console.log("justchat=》接收消息：start " + JSON.stringify(data));

            //会话
            var topic = data.Topic;
            var topic_type = topic.TopicType; //PRIVATE: 私聊
            var topic_id = topic.ID;
            var msgCount = data.MsgCount;
            var msgs = data.Msgs;
            if (msgs.length > 0) {

                //维护maxMsgID
                var maxMsgID = _getMaxID(topic_id);
                for (var i = 0; i < msgs.length; i++) {
                    var msg = msgs[i];
                    var msgid = msg.MsgID;
                    var source = msg.Source;
                    var clientID = msg.ClientID;
                    var msgType = msg.MsgType;

                    // 官方运营
                    if(source == 88888){
                        if(/data\-title\=\"\{(.*)\}\"/g.test(msg.Info)){
                            var sign = /data\-title\=\"\{(.*)\}\"/g.exec(msg.Info)[1];
                            if(sign == '暂离提醒'){
                                // 让控制台的状态改成下班状态。
                                window.parent.postMessage({type:'goOffWork'},"*");
                            }
                            if(!sign) continue
                        }else{
                            continue
                        }
                    }

                    if (msgid > maxMsgID) {
                        maxMsgID = msgid;
                    }
                    if (_msgIsInChatlog(clientID, topic_id) == false) {

                        layui.config({
                            base: '../../script/'
                        }).use(['justchatApiMgr'], function () {
                            var justchatApiMgr = layui.justchatApiMgr;

                            var getMessage = function (nickname, avatar) {
                                var messageItem = {
                                    username: nickname
                                    // , avatar: avatar
                                    , id: topic_id
                                    , type: "friend"
                                    , msgid: msgid
                                    , cid: clientID //模拟消息id，会赋值在li的data-cid上，以便完成一些消息的操作（如撤回），可不填
                                    , content: msg.Info
                                    , mine: mine.id == source ? true : false     //是否我发送的消息，如果为true，则会显示在右方
                                    , fromid: source //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
                                    , timestamp: msg.Timestamp * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
                                    , time: layim.convertStampToTime(msg.timestamp)
                                    , msgType: msgType
                                }
                                // 官方运营
                                if(sign){
                                    messageItem.sign = '[ '+sign+' ]'
                                }
                                layim.getMessage(messageItem);
                            };

                            var nickname = '', portraitUri = '';
                            if(friendsInfo[source]){
                                nickname = friendsInfo[source]['nickname']
                                portraitUri = friendsInfo[source]['portraitUri']
                            }else {
                                portraitUri = ((isAgency && (mine.id == source)) || (!isAgency && (mine.id != source)))?agentDefultImg:playerDefultImg;
                            }

                            getMessage(nickname, portraitUri);
                        })
                    }
                }
                //写入localStorage
                var obj = {};
                if (localStorage.getItem("maxInfo")) {
                    obj = JSON.parse(localStorage.getItem("maxInfo"));
                }
                obj["friend" + topic_id] = maxMsgID;
                localStorage.setItem("maxInfo", JSON.stringify(obj));
            }

            layui.config({
                base: '../../script/'
            }).use(['justchatModel'], function () {
                var justchatModel = layui.justchatModel;
                justchatModel.curTopic = topic;
            });

            console.log("justchat=》接收消息：end");
        },
        //客户端ACK（8）
        justchatClientAct: function (socketMgr, topic) {
            console.log("justchat=》客户端ack");
            var self = this;
            layui.config({
                base: '../../script/'
            }).use(['justchatModel'], function () {
                var justchatModel = layui.justchatModel;
                var id = justchatModel.curTopic.ID;
                var _maxMsgID = _getMaxID(id);
                var data = {
                    Topic: {
                        TOPIC_TYPE: 0,
                        ID: id
                    },
                    MaxMsgID: _maxMsgID
                };
                console.log("justchat=》ID：" + id + " MaxMsgID:" + _maxMsgID);
                socketMgr.send(8, "ChatNTAck", data);
            });

        },
        //发送消息 (5)
        justchatSendMessage: function (socketMgr, res) {
            var self = this;
            layui.config({
                base: '../../script/'
            }).use(['justchatModel'], function () {
                var justchatModel = layui.justchatModel;
                var mine = res.mine; //包含我发送的消息及我的信息
                var to = res.to; //对方的信息
                var cid = res.cid; //对方的信息

                var info = mine.content;
                var msgType = mine.msgType || 0;

                var data = {
                    ClientID: cid,
                    MsgType: msgType,
                    Topic: {
                        TOPIC_TYPE: 0,
                        ID: to.id
                    },
                    Info: info
                };
                socketMgr.send(5, "ChatReq", data);
            });
        },
        //服务端ACK（6）
        justchatServerAck: function (data) {
            console.log("justchat=》服务端ack:"+JSON.stringify(data));

            // 清除消息超时监听。
            var timer = window.sendMessageTimers[data.ClientID]

            if(timer){
                clearTimeout(timer);
                window.sendMessageTimers[data.ClientID] = null;
            }

            var lastMsg = $(".layim-chat-main ul #chat-"+data.ClientID)
            if(lastMsg.hasClass("layim-chat-mine")){
                lastMsg.find('.layim-chat-loading').remove();
                // 频繁发送,错误
                if(data.MsgID == 0){
                    lastMsg.prepend('<i class="layui-icon layui-icon-tips layim-chat-tips"></i>');
                }
            }
            var Topic = data.Topic;
            var topic_id = Topic.ID;
            var ClientID = data.ClientID;
            var MsgID = data.MsgID; // 服务端生成唯一消息id
            var Timestamp = data.Timestamp * 1000; // 消息到达服务端并存储成功时间

            //根据topic和clientID，来更新本地 localStorage 里面对应的 MsgID 和 Timestamp
            // var obj = layui.data('layim-mobile') || {};

            if (localStorage.getItem("layim-mobile") && localStorage.getItem("layim-mobile") != "{}") {
                var obj = JSON.parse(localStorage.getItem("layim-mobile"));
            }
            var chatlog = obj[mine.id].chatlog;
            var history = obj[mine.id].history || {};
            var curChatlog = chatlog["friend" + topic_id];

            // var newhistory = curChatlog[curChatlog.length -1]
            // if(!(newhistory.mine)){
            //     history["friend" + topic_id] = curChatlog[curChatlog.length -1]
            // } else {
            //     history["friend" + topic_id] = $.extend({}, curChatlog[curChatlog.length -1], {
            //         username: friendsInfo[topic_id]['nickname'],
            //         avatar: friendsInfo[topic_id]['portraitUri'],
            //     })
            // }
            // if(!history["friend" + topic_id]){
            // }

            var curHistoryg = history["friend" + topic_id];
            for (var i = 0; i < curChatlog.length; i++) {
                if (curChatlog[i].cid == ClientID) {
                    curChatlog[i].msgid = MsgID;
                    curChatlog[i].timestamp = Timestamp;
                    curChatlog[i].time = layim.convertStampToTime(Timestamp);
                    if(data.MsgID == 0){
                        // 频繁发送,错误
                        curChatlog[i].isSendSuccess = false;
                    }else{
                        // 更新发送状态为发送成功。
                        curChatlog[i].isSendSuccess = true;
                    }

                    break;
                }
            }

            if (curHistoryg.cid == ClientID) {
                curHistoryg.msgid = MsgID;
                curHistoryg.timestamp = Timestamp;
                curHistoryg.time = layim.convertStampToTime(Timestamp);
                curHistoryg.isSendSuccess = true;
            }

            // 频繁发送,错误
            if(data.MsgID == 0){
                curHistoryg.isSendSuccess = false;
            }else{
                curHistoryg.isSendSuccess = true;
            }


            localStorage.setItem("layim-mobile", JSON.stringify(obj));
            // local.history['friend'+topic_id] = curHistoryg
            // layui.data('layim-mobile', {
            //     key: mine.id
            //     , value: local
            // });
        },
        //请求一个会话（3）
        justchatRequestTopic: function (socketMgr, index, justchatModel) {
            var history = _getHistory();
            var historyBykey = history[index];
            var topicIdBykey = historyBykey.id;
            //请求一个会话
            var data = {
                Topic: {
                    TOPIC_TYPE: 0,
                    ID: topicIdBykey
                }
            };
            socketMgr.send(3, "msg.InTopicReq", data);
        },

        //授权成功的回调（2）
        justchatAuthResp: function (data) {
            // console.log('授权回来的数据' + data)
            // console.log(data)
            if(!(data.PortraitUri)){
                if(isAgency){ //我是客服
                    data.PortraitUri = agentDefultImg;
                }else {
                    data.PortraitUri = playerDefultImg;
                }
            }
            mine.id = data.UserID
            mine.username = data.Nickname
            mine.avatar = data.PortraitUri;
            if(mine.id == target_id){
                layer.msg("不能对自己发起对话");
                return
            }
            if(target_id){
                justchatSocketMgr.sendInTopicReq(target_id);
            }
        },

        justchateventErrorST: function (data) {
            layer.msg(data.Msg)
            if(data.Status=='DUP_LOGIN'){
                //放弃重连
                justchatSocketMgr.close()
                $(".justchat-status").html('(未连接)');
            }
        },

        uuid: function () {
            var s = [];
            var hexDigits = "0123456789abcdef";
            for (var i = 0; i < 36; i++) {
                s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
            }
            s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
            s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
            s[8] = s[13] = s[18] = s[23] = "-";

            var uuid = s.join("");
            return uuid;
        }
    };
    exports('justchatFunc', justchatFunc);
});

